package cn.edu.scau.controller;

import cn.edu.scau.common.utils.ApiResponse;
import cn.edu.scau.pojo.dto.LoginDto;
import cn.edu.scau.service.UserService;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @description: 用户控制器
 * @author: yuxiang
 * @create: 2021-03-29 21:05
 **/
@RestController
@RequestMapping("/user")
@Api(value = "user", tags = "user", description = "用户相关")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 普通登陆
     *
     * @param dto
     * @return
     */
    @PostMapping(value = "/login")
    public ApiResponse userLogin(@RequestBody LoginDto dto) {
        ApiResponse response = new ApiResponse();
        String userName = dto.getUsername();
        String passWord = dto.getPassword();
        Subject userSubject = SecurityUtils.getSubject();
        try {
//            userSubject.login(new MyAuthToken(userName, passWord,null, IShiroConst.LOGIN_REALM_NAME));
//            String uid = Optional.ofNullable(userService.findByUsername(userName)).map(e-> e.getId()
//            ).orElse(null);
            response = userService.login(dto);
        } catch (AuthenticationException e) {
            response.setMsg("账号或密码错误");
            response.setEvent(-1);
        }
        return response;
    }

    /**
     * 退出登录
     *
     * @param token
     * @return
     */
    @GetMapping(value = "/logout")
    public ApiResponse userLogout(@RequestParam(value = "token") String token) {
        ApiResponse response = userService.logout(token);
        return response;
    }

    /**
     * 添加用户
     *
     * @return
     */
    @GetMapping(value = "/add")
    public String userLogin(@RequestParam(value = "userName") String userName,@RequestParam(value = "passWord") String passWord) {
        try {
            userService.add(userName, passWord);
        } catch (AuthenticationException e) {
           return "出错";
        }
        return "添加成功";
    }

}
